//
// api: https://developers.weixin.qq.com/minigame/dev/document/open-api/data/wx.getUserInfo.html
//
let self;
cc.Class({
    extends: cc.Component,

    properties: {
        tips: cc.Label,
        content: cc.Node,
        prefab: cc.Prefab,

    },
    
    /*onLoad () {
    	self = this;
    },*/
    
    onLoad () {
    	self = this;
    	
        if (typeof wx === 'undefined') {
            return;
        }

        wx.onMessage( data => {
        	console.log("onMessage command:"+data.command);
            if (data.command == 'getRank') {//获取排行榜
                self.initFriendInfo();
            }else if(data.command == 'setScore'){//上传分数
            	self.uploadWXData(data.maxScore);
            }
        });

        //this.initTips();
        //this.initUserInfo();
        //this.initFriendInfo();
    },

    initTips () {
        let renderTypeStr = 'Canvas';
        if (cc.game.renderType === cc.game.RENDER_TYPE_WEBGL) {
            renderTypeStr = 'WEBGL';
        }
        self.tips.string = `开放数据域当前支持 ${renderTypeStr} 渲染模式`;
    },

    initUserInfo () {
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            lang: 'zh_CN',
            success: (res) => {
            	console.log("进来initUserInfo");
                self.createUserBlock(res.data[0]);
            },
            fail: (res) => {
                console.error(res);
            }
        });
    },

    initFriendInfo () {
        wx.getFriendCloudStorage({
        	keyList:[
        		"maxScore",
        	],
            success: (res) => {
            	console.log("进来了initFriendInfo");
            	console.log(res);
            	//按maxScore从大到小排列
				var data = self.sortList(res.data, false);
				self.content.removeAllChildren();
                for (let i = 0; i < data.length; ++i) {
                	console.log(data[i]);
                    self.createUserBlock(data[i]);
                }
            },
            fail: (res) => {
                console.error(res);
            }
        });
    },
    
    /*onLookGroupBtnClicked(){ //查看群排行按钮(实际是分享)
        cc.log("点击查看群排行按钮");
        cc.loader.loadRes("texture/share",function(err,data){
            wx.shareAppMessage({
                title: "不怕，就来PK！",
                imageUrl: data.url,
                success(res){
                    console.log("转发成功!!!")
                    if(res.shareTickets == null || res.shareTickets == undefined || res.shareTickets == ""){ //没有群信息，说明分享的是个人
                        console.log("排行榜res.shareTickets is null");
                        self.showTipsUI("查看群排行请分享到群"); //自动消失提示框
                    }else{ //有群信息
                        console.log("排行榜res.shareTickets is not null");
                        console.log(res);
                        self.subTitle.string = "群排行榜";
                        if(res.shareTickets.length > 0){
                            console.log("res.shareTickets:" + res.shareTickets);
                            self.lookGroupBtnNode.active = false;
                            wx.postMessage({ message: "groupRank" + res.shareTickets[0] }); //通知子域运行场景groupRank
                        }
                    }
                },
                fail(res){
                    console.log("转发失败!!!")
                } 
            })
        }); 
    },*/


    createUserBlock (user) {
        let node = cc.instantiate(self.prefab);
        node.parent = self.content;
        node.x = 0;

        // set nickName
        let userName = node.getChildByName('userName').getComponent(cc.Label);
        userName.string = user.nickName || user.nickname;
        
        // set maxScore
        let maxScore = node.getChildByName('maxScore').getComponent(cc.Label);
        maxScore.string = 123;
        var dList = user.KVDataList;
		for(var j = 0; j < dList.length; j++){
			if(dList[j].key == "maxScore"){
				maxScore.string = dList[j].value;
				break;
			}
		}

        // set avatar
        cc.loader.load({url: user.avatarUrl, type: 'png'}, (err, texture) => {
            if (err) console.error(err);
            let userIcon = node.getChildByName('mask').children[0].getComponent(cc.Sprite);
            userIcon.spriteFrame = new cc.SpriteFrame(texture);
        });
    },
    
    uploadWXData: function(maxScore){ //上报到微信服务器：历史最高分
    	console.log("maxScore:"+maxScore);
    	var kvDataList = new Array();
    	var a = {};
    	a["key"] = "maxScore";
    	a["value"] = ""+maxScore;
		kvDataList.push(a);
		wx.setUserCloudStorage({
			KVDataList:kvDataList,
			success:function(res){
				console.log("存储数据成功")
			},
			fail:function(res){
				console.log("存储数据失败")
			},
			complete:function(res){
				console.log("存储数据完成")
			}
		});
	},
	
	

	
	sortList: function(ListData, order){ //排序(ListData：res.data;order:false降序，true升序)
		ListData.sort(function(a,b){
			var AMaxScore = 0;
			var KVDataList = a.KVDataList;
			for(var i = 0; i < KVDataList.length; i++){
				if(KVDataList[i].key == "maxScore"){
					AMaxScore = KVDataList[i].value;
				}
			}
	
			var BMaxScore = 0;
			KVDataList = b.KVDataList;
			for(var i = 0; i<KVDataList.length; i++){
				if(KVDataList[i].key == "maxScore"){
					BMaxScore = KVDataList[i].value;
				}
			}
	
			if(order){
				return parseInt(AMaxScore) - parseInt(BMaxScore);
			}else{
				return parseInt(BMaxScore) - parseInt(AMaxScore);
			}
		});
		return ListData;
	},
    
});
